using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using elibrary.Classes;
using elibrary.Models;
using elibrary.Models.Entities;
using PaymentStatus = elibrary.Models.Entities.Payment.PaymentStatus;

namespace elibrary.Models.Managers
{
	public class PaymentManager
	{
		private DataContext ctx;
		private DbSet<Payment> payments;

		public PaymentManager(DataContext ctx)
		{
			this.ctx = ctx;
			this.payments = ctx.payments;
		}

		public void add(Payment payment,bool autoSave=true)
		{
			if (payment.onAdding())
			{
				payments.Add(payment);

				if (autoSave)
					ctx.SaveChanges();
			}
		}

		public void delete(int id,bool autoSave=true)
		{
			delete(get(id),autoSave);
		}

		public void delete(Payment payment,bool autoSave=true)
		{
			if (payment == null)
				return;

			payments.Remove(payment);

			if (autoSave)
				ctx.SaveChanges();
		}

		public Payment get(int id)
		{
			return payments.SingleOrDefault(q => q.id == id);
		}

		public Payment getByOrderStatus(int oid, PaymentStatus status)
		{
			var r = payments.Where(q => q.orderId == oid && q.status == status);

			return r != null && r.Any() ? r.First() : null;
		}

		public List<Dictionary<string,object>> getAllAvailableClient()
		{
			List<Dictionary<string,object>> toReturn = new List<Dictionary<string,object>>();
			List<Payment> available = Utilities.ensureRs<Payment>(payments.Where( 
				q => ((int)q.order.status) >= 1 && ((int)q.order.status) <= 3 ));

			foreach(var payment in available)
			{
				Dictionary<string,object> obj = Utilities.getClientRichObject(new string[]{
					"id","paymentDate","orderId"}, payment);

				obj["amount"] = payment.amountPaid;
				obj["payee"] = payment.payeeName;
				obj["transcode"] = payment.transCode;
				obj["status"] = (int)payment.status;

				toReturn.Add(obj);
			}

			return toReturn;
		}

		public List<Payment> getAllByOrder(int oid)
		{
			var r = payments.Where(q => q.orderId == oid);

			return r != null && r.Any() ? r.ToList() : new List<Payment>();
		}

		public List<Payment> getAllByOrderStatus(int oid, PaymentStatus status)
		{
			var r = payments.Where(q => q.orderId == oid && q.status == status);

			return r != null && r.Any() ? r.ToList() : new List<Payment>();
		}

		public bool hasByOrderId(int oid)
		{
			return payments.Where(q => q.orderId == oid).Any();
		}

		public bool hasByOrderIdStatus(int oid, PaymentStatus st)
		{
			return payments.Where(q => q.orderId == oid && status == st).Any();
		}

	}
}